package com.geeguo.ebuilder.core.common.utils.excelimport;

import cn.idev.excel.FastExcel;
import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.support.ExcelTypeEnum;
import com.geeguo.ebuilder.core.common.constants.CommonConstants;
import com.geeguo.ebuilder.core.common.constants.ContentTypeConstants;
import com.geeguo.ebuilder.core.common.constants.HeaderConstants;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class ExcelImportUtils {

    public static <T> List<ColumnSchema> getColumnSchemas(Class<T> clazz) {
        List<ColumnSchema> schemas = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
                ColumnSchema schema = new ColumnSchema();
                schema.setFieldName(field.getName());
                schema.setColumnName(excelProperty.value()[0]);
                schemas.add(schema);
            }
        }
        return schemas;
    }

    public static <T> void downloadTemplate(HttpServletResponse response, Class<T> clazz, String fileName, String sheetName, T demoData) throws IOException {
        String headFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(ContentTypeConstants.APPLICATION_XLSX);
        response.setHeader(HeaderConstants.CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + headFileName + ".xlsx");
        List<T> demoDataList  = new ArrayList<>();
        if (demoData != null) {
            demoDataList.add(demoData);
        }
        FastExcel.write(response.getOutputStream())
                .head(clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .doWrite(demoDataList);
    }
}
